import {observable, action,toJS} from 'mobx';
import $ from "jquery";
import {message,Modal} from 'antd';
import * as API from '../../apis/board';
import { generateUUID, formatMultLang, decodeMultiLang } from '../../cubeUtil';
import { WeaForm } from 'comsMobx';
import { WeaLocaleProvider,WeaTools } from 'ecCom';
import _ from 'lodash';
const getLabel = WeaLocaleProvider.getLabel;

export default class BoardStore{
    @observable windowHeight=window.innerHeight;
    @observable windowWidth=window.innerWidth;
    @observable timestamp: string=new Date().getTime()+'';
    @observable boardid: string;
    @observable resourceid: string;
    fromPageExpend:string;
    @observable type: string;//关联类型字段值
    @observable defaultTabSet: string;//类型
    tablename:string;//看板对应的查询，查询对应的表名
    reffieldname:string;
    customid:string;
    @observable isTitle:string;//title字段是否为查询列表中那的标题字段
    @observable canAdd:boolean=false;//各个分组底部是否有"添加新数据"的按钮
    addurl:string='';
    @observable datasIdList:any=[];//分组id
    @observable statusList:any=[];
    datas_all:any={};
    @observable groupItems :any = {};//记录移动后的元素分组位置
    @observable datas:any={};
    pageSize=10;
    @observable orderField:any=[];//排序字段
    @observable isAdvanceSearch:any=true;
    @observable orderInfo:any={type:'',fieldid:''};
    boardGrid;
    columnGrids: any = [];
    columnGrids_map:any={};
    @observable loading: boolean = false;
    @observable data_loading: boolean = false;
    @observable item_loading: any ={};
    @observable form = new WeaForm();
    @observable conditionInfo: any = [];

    //@observable isHasQuickSearch: boolean = true;//是否有快捷搜索
    @observable quickSearchData: any = {}; //快速搜索数据
    @observable quicksearchparam: any = {}; //url传递的快速搜索数据
    @observable quickSearchFormData: any = {}; //快速搜索表单数据
    @observable quickSearchDataWithNoChange: any = ''; //仅快速搜索处使用，记录空数据结构，不做改变
    quickSearchConditionData: any = {}; //快速搜索输入的数据(用于浏览框动态参数)
    @observable iconInfo = {
        icon: "icon-coms-ModelingEngine",
        iconColor: "#fff",
        iconBg: "#96358a"
    }

    allStatusMap={};//所有状态信息

    paginationInfo={};//记录每组的分页情况
    @observable windowTitle = '';
    @observable isScroll: boolean = false;//是否显示滚动条
    /**
     *弹框卡片页相关属性
     */
    @observable cardDiag_visible = false;
    @observable cardDiag_url = "";
    /**
     * 权限
     */
    @observable hasRight:boolean=false;//是否有看板后台配置的权限
    @observable hasSearcgRight:boolean=true;//是否有查询列表的查看权限
    /**
     * column拖拽信息start,拖拽结束后与结束时信息对边判断移动的位置
     */
    column_move_info:any;

    /**
     * item拖动前所在的grid
     */
    item_move_old_grid:any;
    item_move_info:any;
    item_move_start_index;

    @observable checkAdvanedData = "";
    @observable params = {} as any;

    /**
     * 初始化看板数据
     */
    @action
    initData=()=>{
        this.loading = true;
        this.quickSearchFormData = {};
        API.checkRight({boardid:this.boardid,dataid:this.resourceid}).then(({ error, status,isRight,customid}) => {
            if (status == '1') {
                this.hasRight=isRight;
                this.data_loading = true;
                this.getConditionInfo(customid,this.afterConditionInit);
            } else {
                message.error(error);
                throw error;
            }
            this.loading = false;
        });
    }
    //初始化时 获取看板数据
    getdata=()=>{
        let isQuickSearch1 = false;
        const quickSearchFormData = toJS(this.quickSearchFormData);
        if (quickSearchFormData && JSON.stringify(quickSearchFormData) !== '{}') {
            isQuickSearch1 = true;
        }
        let copyparams = this.getUrlParam();
        //...this.quicksearchparam?{isQuickSearch: "1",...this.quicksearchparam}:{},
        API.getBoardDatas({...copyparams,boardid:this.boardid,isBoardData:'1',resourceid:this.resourceid,fromPageExpend:this.fromPageExpend,...this.form.getFormParams(),...this.params,...isQuickSearch1 ? { isQuickSearch: "1", ...this.quickSearchFormData } : {}}).then(({ error, status,hasSearcgRight,groupIdList,groupMap,statusList,tablename,reffieldname,type,canAdd,addurl,customid,orderFieldList,isTitle,allStatusMap,pageSize,defaultTabSet,windowTitle,checkAdvanedData}) => {
            if (status == '1') {
                this.hasSearcgRight=hasSearcgRight;
                if(window.location.href.indexOf('wui/index.html')==-1){//不在前端才修改title
                    this.windowTitle = windowTitle;
                }
                this.checkAdvanedData=checkAdvanedData;
                if(hasSearcgRight){//查询列表未配置权限
                    this.pageSize=pageSize<=0?10:pageSize;
                    this.allStatusMap=allStatusMap;
                    this.customid=customid;
                    this.datas_all=groupMap;
                    _.forEach(groupMap,(item,key)=>{
                        this.groupItems[key] = [...item.itemIdList]
                    });
                    this.constructorFirstPage(groupIdList);
                    this.datasIdList=groupIdList;
                    this.statusList=statusList;
                    this.tablename=tablename;
                    this.reffieldname=reffieldname;
                    this.canAdd=canAdd;
                    this.addurl=addurl;
                    this.type=type;
                    this.defaultTabSet=defaultTabSet;
                    //this.isHasQuickSearch = quickSearch.isHasQuickSearch;
                    this.orderField =orderFieldList;
                    this.isTitle=isTitle;
                    this.initBoard();
                }else{
                    this.data_loading = false;
                }
            } else {
                message.error(error);
                throw error;
            }
        });
    }


    @action
    getIconInfo = (modeid) => {
        API.getAppInfoByID({ modeid }).then((data: any) => {
            if (data.status == "1") {
                this.iconInfo = {
                    icon: data.icon || "icon-coms-ModelingEngine",
                    iconColor: data.iconColor || "#fff",
                    iconBg: data.iconBg || "#96358a"
                };
            }
        })
    }

    @action
    setQuickSearchInfo = (data = []) => {
        this.quickSearchData.quicksearchinfo = data;
    };

     /**
     * 组装第一页数据
     */
    @action
    constructorFirstPage=(groupIdList)=>{
        let datas_temp={};
        groupIdList.forEach(groupid=>{//遍历每一组
            const column=this.datas_all[groupid];
            this.paginationInfo[groupid]={current:0,total:Math.ceil(column.itemIdList.length/this.pageSize)};
            if(column.itemCount>this.pageSize){
                let itemIdList=column.itemIdList.slice(0,this.pageSize);
                let item={};
                itemIdList.forEach(i=>{
                    item[i]=column.item[i];
                });
                datas_temp[groupid]={...column,item,itemIdList}
            }else{
                datas_temp[groupid]=column;
            }
        });
        this.datas=datas_temp;
    }

    /**
     * 翻页
     */
    changePage=(groupid)=>{
        if(groupid.endsWith('_new'))return;
        const page=this.paginationInfo[groupid];
        page.current+=1;
        if(page.current<page.total){
            let itemIdList_temp=this.datas_all[groupid].itemIdList.slice(page.current*this.pageSize,(page.current+1)*this.pageSize);
            let item={};
            itemIdList_temp.forEach(i=>{
                item[i]=this.datas_all[groupid].item[i];
            });
            this.datas[groupid].item={...this.datas[groupid].item,...item};
            this.datas[groupid].itemIdList=[...this.datas[groupid].itemIdList,...itemIdList_temp];
            setTimeout(() => {
                itemIdList_temp.forEach(i=>{
                    const grid=this.columnGrids_map["column_content_"+groupid];
                    const element:any=document.getElementById('item_'+i);
                    grid.add([element], {index:grid.getItems().length});
                });
            }, 500);
            return true;
        }
        return false;
    }

    /**
     * 初始化看板拖动元素
     */
    @action
    initBoard = () => {
        const Muuri: any = window['Muuri'];
        var borderContainer: any = document.querySelector('.cube_board_container');
        var board = borderContainer.querySelector('.board');
        var itemContainers = Array.prototype.slice.call(borderContainer.querySelectorAll('.board-column-content'));
        const _this=this;
        itemContainers.forEach(container=>this.initItem(container));

        this.boardGrid = new Muuri(board, {
            layout: function (items, gridWidth, gridHeight) {
                // The layout data object. Muuri will read this data and position the items
                // based on it.
                var layout:any = {
                  // The layout item slots (left/top coordinates).
                  slots: [],
                  // The layout's total width.
                  width: 0,
                  // The layout's total height.
                  height: 450,
                  // Should Muuri set the grid's width after layout?
                  setWidth: true,
                  // Should Muuri set the grid's height after layout?
                  setHeight: false
                };
                // Calculate the slots.
                var item;
                var m;
                var x = 0;
                var y = 0;
                var w = 0;
               // var h = 0;
                for (var i = 0; i < items.length; i++) {
                  item = items[i];
                  x += w;
                  //y += h;
                  m = item.getMargin();
                  w = item.getWidth() + m.left;
                //  h = item.getHeight() + m.top + m.bottom;
                  layout.slots.push(x, y);
                }
                // Calculate the layout's total width and height.
                layout.width = x + w;
                //layout.height = y + h;
                return layout;
            },
            layoutDuration: 400,
            layoutOnResize:false,
            layoutEasing: 'ease',
            dragEnabled: true,
            dragSortInterval: 0,
            dragStartPredicate:function (item, event) {
                if (!_this.hasRight) {
                    return false;
                }
                if(_this.defaultTabSet == '2'){
                    return false;
                }
                // Prevent first item from being dragged.
                if (_this.boardGrid.getItems().indexOf(item) === _this.boardGrid.getItems().length-1||_this.boardGrid.getItems().indexOf(item) === _this.boardGrid.getItems().length-2) {
                  return false;
                }
                // For other items use the default drag start predicate.
                return Muuri.ItemDrag.defaultStartPredicate(item, event,{
                    handle: '.board-column-header'
                });
            },
            dragSortPredicate: function (item) {
              var result = Muuri.ItemDrag.defaultSortPredicate(item, {
                action: 'swap',
                threshold: 50
              });
              return result && (result.index === _this.boardGrid.getItems().length-1||result.index === _this.boardGrid.getItems().length-2) ? false : result;
            },
            dragReleaseDuration: 400,
            dragReleaseEasing: 'ease'
        }).on('dragMove', function (item, event) {
            if(event){
                let borderDiv=$('#cube_board_container');
                if((event.center.x+item.getWidth()/2)>window.innerWidth){
                    borderDiv.scrollLeft(borderDiv.scrollLeft()+20);
                }
                if(event.center.x-item.getWidth()/2<0){
                    borderDiv.scrollLeft(borderDiv.scrollLeft()-20);
                }
            }
        }).on('dragStart', function (item) {
            _this.column_move_info=[];
        }).on('dragReleaseEnd', function (item) {
            if(_this.column_move_info.length!=0){
                let startD=_this.column_move_info[0];
                let endD=_this.column_move_info[_this.column_move_info.length-1];
                if(startD.fromIndex!=endD.toIndex){
                    _this.loading = true;
                    let leftgroupid=endD.toIndex==0?"":_this.boardGrid.getItems()[endD.toIndex-1]._element.getAttribute('id').replace('column_','')
                    API.saveGroupOrder({ boardid:_this.boardid,resourceid:_this.resourceid,type:_this.type,groupid:item._element.getAttribute('id').replace('column_',''),
                    leftgroupid}).then(({ error, status,errorCode }) => {
                        if (status == '1'&&errorCode!='-1') {
                            message.success(getLabel(389171, "排序保存成功！"));
                        } else {
                            message.error(error);
                            throw error;
                        }
                        this.loading = false;
                    });
                }
            }
        }).on('move', function (data) {
            _this.column_move_info.push(data);
        });
        this.ungroupedShowOrHide();
    }

    /**
     * 初始化item元素
     */
    initItem=(container,isSearch=false)=>{
        const Muuri: any = window['Muuri'];
        const _this=this;
        var muuri: any = new Muuri(container, {
            items: '.board-item',
            layoutDuration: 400,
            layoutEasing: 'ease',
            dragEnabled: true,
            dragSortInterval: 0,
            dragStartPredicate:function (item, event) {
                if (!_this.hasRight) {
                    return false;
                }
                if($(item._element).attr('data-showlevel')<2){
                    return false;
                }
                if(event.target.parentNode&&event.target.parentNode.id&&event.target.parentNode.id=='boardItemTitle'){
                    return;
                }
                return Muuri.ItemDrag.defaultStartPredicate(item, event,{
                    handle: '.board-item-content'
                });
            },
            dragSort: function () {
                return _this.columnGrids;
            },
            dragContainer: document.querySelector('.cube_board_container'),
            dragReleaseDuration: 400,
            dragReleaseEasing: 'ease'
        }).on('dragStart', function (item) {
            item.getElement().style.width = item.getWidth() + 'px';
            item.getElement().style.height = item.getHeight() + 'px';
            _this.item_move_old_grid=item.getGrid();
            _this.item_move_info=[];
            _this.item_move_start_index=item.getGrid().getItems().indexOf(item);
        }).on('dragReleaseEnd', function (item) {
            item.getElement().style.width = '';
            item.getElement().style.height = '';
            _this.columnGrids.forEach(function (muuri: any) {
                muuri.refreshItems();
            });
            if(item.getGrid()!=_this.item_move_old_grid){//移出到另一个column中
                let currentId = item._element.getAttribute('id').replace('item_', '');
                let i=item.getGrid().getItems().indexOf(item);
                let previousId=item.getGrid().getItems()[i-1]?item.getGrid().getItems()[i-1]._element.getAttribute('id'):'';
                let nextId=item.getGrid().getItems()[i+1]?item.getGrid().getItems()[i+1]._element.getAttribute('id'):'';
                let gridid=_this.item_move_old_grid._element.getAttribute('id').replace('column_content_','');
                let groupid = item.getGrid()._element.getAttribute('id').replace('column_content_','');

                _this.saveItemOrder(true,currentId,groupid,previousId,nextId);

                //动态变换选项值
                const datastemp = _this.datas;//前端缓存数据
                let itemtemp = datastemp[groupid].item[currentId];
                const getTitle = (dataid) => _this.datas_all[dataid] ? _this.datas_all[dataid].title : datastemp[dataid].title;//是否后端数据，不是则从前端新建的分组拿
                const title_gridid = getTitle(gridid);
                const title_groupid = getTitle(groupid);
                if (title_gridid == '未分组' && itemtemp['statusText'] == '') {//如果是从未分组移动到其他分组
                    itemtemp['statusText'] = title_groupid
                } else {//分组间互相移动

                    for(var index in itemtemp){
                        if (itemtemp.hasOwnProperty(index)) {
                            if (itemtemp[index] == title_gridid) {
                                if (title_gridid == '未分组') {
                                itemtemp[index] = '';
                            }else{
                                    itemtemp[index] = title_groupid
                                }
                            }
                        }
                    }
                }

                datastemp[groupid].item[currentId] = itemtemp;
                _this.datas = {...datastemp};

                //翻页问题处理
                let divscroll:any = document.getElementById("board-column-content-scroll"+gridid);
                let divHeight = divscroll.clientHeight;
                if( divHeight < (_this.windowHeight - 190)){
                    _this.changePage(gridid);
                }
                // }
            }else if(_this.item_move_info.length!=0){//自己column中移动
                let startD=_this.item_move_info[0];
                let endD=_this.item_move_info[_this.item_move_info.length-1];
                if(startD.fromIndex!=endD.toIndex&&_this.item_move_start_index!=endD.toIndex){
                    let currentId=item._element.getAttribute('id');
                    let i=item.getGrid().getItems().indexOf(item);
                    let previousId=item.getGrid().getItems()[i-1]?item.getGrid().getItems()[i-1]._element.getAttribute('id'):'';
                    let nextId=item.getGrid().getItems()[i+1]?item.getGrid().getItems()[i+1]._element.getAttribute('id'):'';
                    _this.saveItemOrder(false,currentId,item.getGrid()._element.getAttribute('id'),previousId,nextId);
                }
            }
            if(_this.item_move_old_grid._element.getAttribute('id')=='column_content_ungrouped'){
                _this.ungroupedShowOrHide();
            }
        }).on('move', function (data) {
            _this.item_move_info.push(data);
        }).on('receive', function (data) {
            _this.changeStatus(data);
        }).on('layoutStart', function () {
            _this.boardGrid.refreshItems().layout();
        }).on('dragMove', function (item, event) {
            if(event){
                //上下拖动
                let pElement=$(item.getGrid()._element.parentNode);
                if(event.center.y+item.getHeight()/2>item.getGrid()._top+pElement.scrollTop()+$(pElement).height()){
                    pElement.scrollTop(pElement.scrollTop()+20);
                }
                if(event.center.y-item.getHeight()/2<item.getGrid()._top+pElement.scrollTop()){
                    pElement.scrollTop(pElement.scrollTop()-20);
                }
                //左右拖动
                let borderDiv=$('#cube_board_container');
                if((event.center.x+item.getWidth()/2)>window.innerWidth){
                    borderDiv.scrollLeft(borderDiv.scrollLeft()+20);
                }
                if(event.center.x-item.getWidth()/2<0){
                    borderDiv.scrollLeft(borderDiv.scrollLeft()-20);
                }
            }
        });
        if(!isSearch){
            _this.columnGrids.push(muuri);
            _this.columnGrids_map[container.getAttribute('id')]=muuri;
        }
    }

    /**
     * 初始化查询条件
     */
    @action
    getConditionInfo=(customid,callback?)=>{
        this.data_loading = true;
        API.getConditionInfo({"customid":customid}).then(({ error, status,conditionInfo,noRight}) => {
            if (status == '1') {
                if(noRight||conditionInfo[0].items.length==0){
                    this.isAdvanceSearch=false;
                }else{
                    this.conditionInfo=conditionInfo;
                    this.form.initFormFields(conditionInfo);
                    this.form.isFormInit = true;
                }
                this.qiuckSearch();
                callback && callback(customid);
            } else {
                message.error(error);
                throw error;
            }
            this.data_loading = false;
        })
    }

    getUrlParam=()=>{
        const urlParams = WeaTools.getUrlParams();
        let copyparams = {};
        for (const key in urlParams) {
            try {
                if(key!='boardid'&&key!='fromPageExpend'&&key!='rootId'&&key!='_key'&&key!='remove'){
                    copyparams[key] = decodeURI(urlParams[key]);
                }
            } catch (error) {
                copyparams[key] = urlParams[key];
            }
        }
        return copyparams;
    }

    qiuckSearch=()=>{
        let copyparams = this.getUrlParam();
        API.getBoardQuickSearch({...copyparams,boardid:this.boardid}).then(({status,error,quickSearch,quicksearchparam})=>{
            if (status == '1') {
                this.quickSearchData = quickSearch;
                this.quickSearchFormData = quicksearchparam;
                this.quickSearchDataWithNoChange = JSON.stringify(this.clearDefaultValue(quickSearch.quicksearchinfo));//转换为字符串防止对象修改
            } else {
                message.error(error);
                throw error;
            }

        })
    }

    /**
     * 查询
     */
    @action
    doSearch=(params={})=>{
        this.datas={};
        this.groupItems = {};
        this.datasIdList=[];
        this.data_loading = true;
        let isQuickSearch1 = false;
        const quickSearchFormData = toJS(this.quickSearchFormData);
        if (quickSearchFormData && JSON.stringify(quickSearchFormData) !== '{}') {
            isQuickSearch1 = true;
        }
        let copyparams = this.getUrlParam();
        //...this.quicksearchparam?{isQuickSearch: "1",...this.quicksearchparam}:{},
        API.getBoardDatas({...copyparams,isFromSearch:'1',isBoardData:'1',boardid:this.boardid,resourceid:this.resourceid,fromPageExpend:this.fromPageExpend,...this.form.getFormParams(),...params,...isQuickSearch1 ? { isQuickSearch: "1", ...this.quickSearchFormData } : {}}).then(({ error, status,groupIdList,groupMap,checkAdvanedData,defaultTabSet}) => {
            if (status == '1') {
                this.checkAdvanedData=checkAdvanedData;
                this.datas_all=groupMap;
                _.forEach(groupMap,(item,key)=>{
                    this.groupItems[key] = [...item.itemIdList]
                });
                this.constructorFirstPage(groupIdList);
                this.datasIdList=groupIdList;
                this.timestamp=new Date().getTime()+'';
                this.defaultTabSet = defaultTabSet;
                this.initBoard();
            } else {
                message.error(error);
                throw error;
            }
            //this.data_loading = false;
        })
    }

    /**
     * 未分组隐藏\显示
     */
    ungroupedShowOrHide=()=>{
        let ungroupedGrid;
        if(this.hasRight){
            ungroupedGrid=this.boardGrid.getItems()[this.boardGrid.getItems().length-2];
        }else{
            ungroupedGrid=this.boardGrid.getItems()[this.boardGrid.getItems().length-1];
        }
        if(this.columnGrids_map['column_content_ungrouped'].getItems().length>0 || this.defaultTabSet == "2"){
            this.boardGrid.show(ungroupedGrid);
        }else{
            this.boardGrid.hide(ungroupedGrid);
        }
        this.data_loading = false;
    }

    /**
     * 添加分组
     */
    addColumn=(title)=>{
        const newId=generateUUID()+"_new";
        let newStatus={};
        this.statusList.forEach(element => {
            newStatus[element]=0;
        });
        this.datas[newId]={id:newId,title:decodeMultiLang(title),item:[],itemCount:0,status:newStatus,itemIdList:[]};
        this.datasIdList.push(newId);
        this.loading = true;
        API.addGroup({ boardid:this.boardid,resourceid:this.resourceid,title,type:this.type,tempid:newId,fromPageExpend:this.fromPageExpend}).then(({ error, status }) => {
            if (status == '1') {
                message.success(getLabel(389172, "分组添加成功！"));
            } else {
                message.error(error);
                throw error;
            }
            this.loading = false;
        })
    }

    /**
     * 删除Column元素
     */
    removeColumn=(id)=>{
        const mythis = this;
        Modal.confirm({
            title: getLabel(129890, '确定要删除吗?', 'label'),
            okText: getLabel(382958, '确定'),
            okType: 'danger',
            cancelText: getLabel(201, "取消"),
            onOk() {
                mythis.loading = true;
                const params = {
                    id, customid: mythis.customid
                };
                API.deleteGroup(params).then(({ error, status }) => {
                    if (status == '1') {
                        message.success(getLabel(83472, "删除成功！"));
                        mythis.doSearch();
                    } else {
                        message.error(error);
                        throw error;
                    }
                    mythis.loading = false;
                })
            }
        });
    }

    /**
     * 移动分组数据
     */
    @action
    changeGroup=(fromGroupid,toGroupid,fromTitle,toTile)=>{
        if(this.columnGrids_map['column_content_'+fromGroupid].getItems().length==0){
            message.warn(getLabel(389173, "当前分组中无数据！"));
            return;
        }
        const mythis = this;
        Modal.confirm({
            title:formatMultLang(getLabel(389174, "确定要将【{0}】中的数据转移至【{1}】吗？"),fromTitle,toTile),
            okText: getLabel(382958, '确定'),
            okType: 'danger',
            cancelText: getLabel(201, "取消"),
            onOk() {
                //若果是从未分组移动到别处的要把无分组数据的数据整理出来
                let ids:any=[];
                if(fromGroupid=='ungrouped'){
                    mythis.columnGrids_map.column_content_ungrouped.getItems().forEach(item=>{
                        const id=item._element.getAttribute('id').replace('item_','');
                            ids.push(id);
                    });
                    const ungroupedPage=mythis.paginationInfo['ungrouped'];
                    if(ungroupedPage.current<ungroupedPage.total){
                        let remainIds=mythis.datas_all['ungrouped'].itemIdList.slice((ungroupedPage.current+1)*mythis.pageSize);
                        remainIds.forEach(element => {
                                ids.push(element);
                        });
                    }
                }

                let data = _.assign({},mythis.datas_all[fromGroupid].item,mythis.datas[fromGroupid].item);
                const filterItems :any = {};
                _.map(mythis.groupItems[fromGroupid],(item,index)=>{
                    filterItems[item] = data[item]
                });
                API.changeGroup({data:JSON.stringify(filterItems),defaultTabSet:mythis.defaultTabSet,tablename:mythis.tablename,fromGroupid,toGroupid,boardid:mythis.boardid,customid:mythis.customid,ids:ids.join(',')}).then(({ error, status, msg }) => {
                    if (status == '1') {
                        if(msg){
                            message.success(msg);
                        }else{
                            message.success(getLabel(389175, "转移成功！"));
                        }
                        mythis.doSearch();
                    } else {
                        message.error(error);
                        throw error;
                    }
                    mythis.data_loading = false;
                })
            }
        });
    }

    /**
     * 添加任务元素（Item元素）
     */
    @action
    addItem=(data)=>{
        this.cardDiag_visible=true;
        this.cardDiag_url=this.addurl.replace('.html','.jsp')+data.id+"&boardcustomid="+this.customid;
        if(this.defaultTabSet == "2"){
            this.cardDiag_url = this.cardDiag_url.replace('#{defaultTabField}',data.selectValue);
        }
        // setTimeout(() => {
        //     document.getElementsByClassName('ant-modal')[0]['style'].top='30px';
        // }, 100);
    }

    /**
     * 标题字段点击弹框
     */
    cube_board_open_dialog=(url,id,groupid)=>{
        url+="&boardid="+this.boardid+"&boardgroup="+groupid+"&boardcustomid="+this.customid;
        this.cardDiag_visible=true;
        this.cardDiag_url=url.replace('.html','.jsp');
        // setTimeout(() => {
        //     document.getElementsByClassName('ant-modal')[0]['style'].top='30px';
        // }, 100);
    }


    /**
     * 卡片页保存回调函数    iscreate:1新建  2编辑
     */
    @action
    cardSaveFun=(billid,iscreate,boardid,boardgroup,boardcustomid,btntype?)=>{
        if(iscreate=='1'){//新增的话异步加载新增的数据。
            // this.data_loading = true;
            // API.getChengedItems({boardid,billid}).then(action(({ error, status,allItem,idList}) => {
            //     if (status == '1') {
            //         idList.forEach((item,index)=>{
            //             boardgroup=allItem[item]['groupid'];
            //             allItem[item]['iscreate']='1';
            //             let status=allItem[item]['status'];
            //             if(this.datas[boardgroup].status[status]!=undefined){
            //                 this.datas[boardgroup].status[status]=this.datas[boardgroup].status[status]+1
            //             }
            //             this.datas[boardgroup].itemCount=this.datas[boardgroup].itemCount+1;
            //             if(!this.datas[boardgroup]['item'])this.datas[boardgroup]['item']={};
            //             this.datas[boardgroup]['item'][item]=allItem[item];
            //             let ids=[item];
            //             this.columnGrids_map['column_content_'+boardgroup].getItems().forEach(item=>{
            //                 const id=item._element.getAttribute('id').replace('item_','');
            //                 ids.push(id);
            //             });
            //             this.datas[boardgroup].itemIdList=ids;
            //         });
            //     } else {
            //         message.error(error);
            //         throw error;
            //     }
            //     this.data_loading = false;
            // }))
            this.doSearch();
        }else{//编辑的话由于情况太多，涉及明细就状态等，编辑保存直接刷新
            this.doSearch();
        }
        if(!(btntype && (btntype == '3' || btntype == '4'))){
            this.cardDiag_visible=false;
        }
    }

    /**
     * 保存任务元素排序,优先排在上一个的下边，或排在下一个的上边，或排在第一个
     */
    saveItemOrder=(isChangeGroup,itemid,groupid,previousId,nextId)=>{
        itemid=itemid.replace('item_','');
        previousId=previousId.replace('item_','');
        nextId=nextId.replace('item_','');
        groupid=groupid.replace('column_content_','');
        this.loading = true;
        API.saveItemOrder({boardid:this.boardid,customid:this.customid,resourceid:this.resourceid,reffieldname:this.reffieldname,tablename:this.tablename,isChangeGroup,itemid,groupid,previousId,nextId}).then(({ error, status }) => {
            if (status == '1') {
                message.success(getLabel(389171, "排序保存成功！"));
            } else {
                message.error(error);
                throw error;
            }
            this.loading = false;
        })

    }

    /**
     * 点击排序
     */
    @action
    changeOrder=(fieldid,fieldlabelname,fieldname,viewtype,fielddbtype,type)=>{
        this.orderInfo['fieldid']=fieldid;
        this.orderInfo['fieldlabelname']=fieldlabelname;
        this.orderInfo['fieldname']=fieldname;
        this.orderInfo['viewtype']=viewtype;
        this.orderInfo['fielddbtype']=fielddbtype;
        this.orderInfo['type']=type;
        this.doSearch({orderFieldName:fieldname,orderType:type,orderViewType:viewtype});
    }

    /**
     * 清除排序信息
     */
    clearOrderInfo=()=>{
        this.orderInfo={type:'',fieldid:''};
        this.doSearch();
    }

    /**
     * 计数状态修改
     */
    @action
    changeStatus=(data)=>{
        let itemId=data.item._element.getAttribute('id').replace('item_','');
        let fromGroupId=data.fromGrid._element.getAttribute('id').replace('column_content_','');
        let toGroupId=data.toGrid._element.getAttribute('id').replace('column_content_','');
        let fromGroup=this.datas[fromGroupId];
        let toGroup=this.datas[toGroupId];
        let item=fromGroup.item[itemId];
        const status=item.status;
        fromGroup.itemCount-=1;
        fromGroup.status[status]-=1;
        toGroup.itemCount=toGroup.itemCount?toGroup.itemCount+1:1;
        toGroup.status[status]+=1;
        if(!toGroup.item){
            toGroup['item']={};
        }
        toGroup.item[itemId]=item;
        _.remove(this.groupItems[fromGroupId],(item)=>item == itemId);
        this.groupItems[toGroupId].push(itemId);
    }

    /**
     * 修改分组名称
     */
    updateGroupName=(groupid,name)=>{
        this.loading = true;
        API.updateGroupName({groupid,name}).then(({ error, status }) => {
            if (status == '1') {
                message.success(getLabel(83551,"保存成功！"));
            } else {
                message.error(error);
                throw error;
            }
            this.loading = false;
        })
    }


     /**
     * 查询条件获取后处理
     */
    @action
    afterConditionInit = (customid: any) => {
        this.getConditionParams(customid, (dataSource) => {
            let dataSourceParams = {};
            for (let field in dataSource) {
                if (Array.isArray(dataSource[field])) {
                    dataSourceParams[field] = dataSource[field].join(',');
                } else if (typeof dataSource[field] == 'object') {
                    dataSourceParams[field] = dataSource[field].value;
                } else {
                    dataSourceParams[field] = dataSource[field];
                }
                //多部门单独处理
                if (field.startsWith('dbm_con_')) {
                    this.params[field] = dataSourceParams[field];
                }
            }
            this.getdata();
        });
    }

    /**
     * 查询查询列表查询条件默认值设置
     */
    @action
    getConditionParams = (customid: any, callback?: (params?: any) => void) => {
        API.getConditionParams({ "customid":customid}).then(({ error, status, dataSource }) => {
            if (status == '1') {
                let newDataSource = { ...toJS(this.params), ...dataSource };
                let otherData={};
                for (let field in newDataSource) {
                    if (this.form.has(field)) {
                        if(Array.isArray(dataSource[field])){
                            const _field = this.form.select(field)
                            _field.set(dataSource[field]);
                        }else{
                            otherData[field]=dataSource[field];
                        }
                    }
                }
                this.form.updateFields(otherData,false);
                callback && callback(newDataSource)
            } else {
                message.error(error)
                throw error;
            }
        })
    }

    clearDefaultValue = (datas = []) => {
        const resetToEmpty = (item) => {
            let { fieldhtmltype, fieldtype, value = '' } = item;
            if ((fieldhtmltype == '1' && fieldtype != '1')//数值类型
                || (fieldhtmltype == '5' && fieldtype == '1')//下拉框
                || (fieldhtmltype == '4' && fieldtype == '1') //勾选框
                || (fieldhtmltype == '5' && fieldtype == '2') //多选框
                || (fieldhtmltype == '5' && fieldtype == '3') //单选框
            ) {
                if (fieldhtmltype == '1' && fieldtype != '1') {
                    item.value = '-1';
                } else {
                    item.value = '';
                }
            } else if (fieldhtmltype == '3' && fieldtype == '1') {//人员 ["-5",""]||[]
                if (value[0] == '-5') {//全部 ["0", null]
                    item.value = ["-5", ""];
                } else {
                    item.value = ["0"];
                }
            } else if (fieldhtmltype == '3' && fieldtype == '2') {//创建日期
                item.value = ["0"];
            } else if (item.hasOwnProperty('replaceDatas')) {
                item.replaceDatas = [];
            } else {
                item.value = '';
            }
            return item;
        };
        const res = datas.map((data: any) => {
            if (data.hasOwnProperty('searchGroup')) {
                data.searchGroup = data.searchGroup.map((item: any) => {
                    return resetToEmpty(item);
                })
            } else {
                data = resetToEmpty(data);
            }
            return data;
        });
        return res;
    };

    @action
    changeConditioninfo=(fieldid,v)=>{
        this.conditionInfo[0] && this.conditionInfo[0].items && this.conditionInfo[0].items.map(item => {
            const { domkey } = item;
            if (domkey[0] == "con_" + fieldid) {
                this.form.$("con_" + fieldid).set(v);
            }
        });
    }

    @action
    changeConditioninfoForBrowser=(fieldid,ids,data,valueSpan)=>{
        this.conditionInfo[0] && this.conditionInfo[0].items && this.conditionInfo[0].items.map(item => {
            const { domkey } = item;
            if (domkey[0] == "con_" + fieldid) {
                this.form.$("con_" + fieldid).value = ids;
                this.form.$("con_" + fieldid).valueObj = data;
                this.form.$("con_" + fieldid).valueSpan = valueSpan;
            }
        })
    }
}
